//
//  MNDShareWebViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/25.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDShareWebViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
#import "WeiboSDK.h"
#import "MNDShareModel.h"
#import "MNDLoginUserModel.h"
#import "RSAUtil.h"
#import "MNDWebViewController.h"
#import "MNDRegisterViewController.h"
#import "SYWebLoadingProgress.h"
#import "MNDInvestListViewController.h"

#define kShareClick @"app://minidai.share"
#define kShareLink  @"touzimobile/#/yaoqing"
//静态页面如新手指南等的返回事件
#define kWebPageBack     @"app://minidai.back"
//跳转论坛
#define kRedirectToBBS   @"bbs.miniwangdai.com/forum/detailed?forum_code=58ec75a09f63a"

#define kBBSLogin        @"miniwangdai.com/login"

/*! 注册 */
#define kWebPageRegister @"app://minidai.register"
/*! 跳转密友圈 */
#define kWebPageForum    @"app://minidai.forum"

#define kPCHomePage      @"https://www.miniwangdai.com/"
/*! 邀请列表 */
#define kInvitationList  @"app://invitation_list"

#define kQRCodeImage     @"app://download_QRcode"


@interface MNDShareWebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (strong, nonatomic) SYWebLoadingProgress *webLoadingProgress;

@property(nonatomic, assign) BOOL isJumpToOtherPage;

//邀请有礼页面跳转到邀请列表页面返回
@property(nonatomic, assign) BOOL isJumpToInvest;

//记录标题
@property (nonatomic, strong) NSString *titleStr;

@end

@implementation MNDShareWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
    
    [self initialWebView];
    if (self.naviBarHidden) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.titleStr = self.title;
}

- (void)initialWebView {
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.webView];
    self.webView.scalesPageToFit = YES;
    self.webView.delegate = self;
    self.webView.scrollView.scrollEnabled = NO;
    if ([MNDLoginUserModel isUserLogin]) {
        MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        NSString *userCode = [self rsaEncode: user.user_code];

        NSString *urlStr = [NSString stringWithFormat:@"%@%@", BroswerHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
        NSURL *url = [NSURL URLWithString: urlStr];
        NSMutableURLRequest *reRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];

        [reRequest setValue:userCode forHTTPHeaderField:@"USERCODE"];

        [self.webView loadRequest:reRequest];

    } else {
        NSString *urlStr = [NSString stringWithFormat:@"%@%@", BroswerHeadURL, [NSString urlEncodeStr:self.webViewUrl]];
        NSURL *url = [NSURL URLWithString: urlStr];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
        [self.webView loadRequest:request];
    }
    
    [self.webView beginLoading];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
  
    if (self.isJumpToOtherPage) {
        self.isJumpToOtherPage = NO;
        [self.navigationController setNavigationBarHidden:self.naviBarHidden animated:YES];
    }
    
    if (self.isJumpToInvest) {
        self.isJumpToInvest = NO;
        self.title = _titleStr;
        self.webView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64);
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)backAction :(id)sender {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        self.title = @"";
        self.automaticallyAdjustsScrollViewInsets = NO;
        [self.navigationController setNavigationBarHidden:self.naviBarHidden animated:YES];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    
    if ([self.navigationController.navigationBar isHidden]) {
        _webLoadingProgress.frame = CGRectMake(0, 20, kScreenWidth, 2);
        
    } else {
        CGFloat yPosition = 64.0;
        if (kScreenHeight >= 812) {
            yPosition = 88;
        }
        _webLoadingProgress.frame = CGRectMake(0, yPosition, kScreenWidth, 2);
        //        [self.view.layer insertSublayer:_webLoadingProgress atIndex:0];
    }
    [self.webView.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [self.webLoadingProgress startProgressAnimation];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress completedProgressAnimation];
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];
    
    [webView endLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"error: %@", error);
    [self.webLoadingProgress completedProgressAnimation];
    
    if (error.code == -999) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
       [self.navigationController setNavigationBarHidden:NO animated:YES];
    });
    
    WeakSelf(self);
    [webView configBlankPage:SYBlankPageTypeNetworkError hasData:NO reloadButtonBlock:^(id sender) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.webView beginLoading];
            [weakself.webView reload];
        });
    }];
}

- (NSMutableURLRequest *)addHTTPHeaderFieldWithRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    //来源加入header
    if (kDevice_iPad) {
        [mutableRequest addValue:@"iPad" forHTTPHeaderField:@"WERTYUIOP"];
    } else {
        [mutableRequest addValue:@"iPhone" forHTTPHeaderField:@"WERTYUIOP"];
    }
    
    return mutableRequest;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSMutableURLRequest *mutableRequest = [self addHTTPHeaderFieldWithRequest:request];
    
    request = [mutableRequest copy];
    
    NSLog(@"header: %@", request.allHTTPHeaderFields);
    
    NSLog(@"url: %@", request.URL.absoluteString);
    
    NSString *absoluteString = request.URL.absoluteString;
    
    if ([absoluteString isEqualToString:kPCHomePage]) {
        
        return NO;
    }
    
    if ([absoluteString isEqualToString:kShareClick]) {
        [self socialShareAction];
        return NO;
    }
    
    if ([absoluteString containsString:kShareLink]) {
        if ([MNDLoginUserModel isUserLogin]) {
            self.title = @"邀请有奖";
            [self.navigationController setNavigationBarHidden:NO animated:YES];
            self.automaticallyAdjustsScrollViewInsets = YES;
        } else {
            self.isJumpToOtherPage = YES;
            [self goLoginVC];
            return NO;
        }
    } else {
        self.title = @"";
        self.automaticallyAdjustsScrollViewInsets = NO;
        [self.navigationController setNavigationBarHidden:self.naviBarHidden animated:NO];
    }
    
    if ([absoluteString containsString:kWebPageBack]) {
        if (webView.canGoBack) {
            [webView goBack];
        } else {
            [self backAction:nil];
        }
    }
    
    if ([absoluteString containsString:kRedirectToBBS]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
            webVC.webViewUrl = absoluteString;
            
            if ([MNDLoginUserModel isUserLogin]) {
                MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
                NSString *userCode = [self rsaEncode: user.user_code];
                NSString *username = [self rsaEncode: user.user_name];
                NSString *userId = [self rsaEncode:   user.user_id];
                
                webVC.circleEncodeUserCode = userCode;
                webVC.circleEncodeUserName = username;
                webVC.circleEncodeUserId = userId;
            }
            self.isJumpToOtherPage = YES;
            [self.navigationController pushViewController:webVC animated:YES];
        });
        
        return NO;
    }
    
    if ([absoluteString containsString:kWebPageRegister]) {
        
        if ([MNDLoginUserModel isUserLogin]) {
            [NetworkProgressHUD showHudMsg:@"您已经注册过了"];
            return NO;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.isJumpToOtherPage = YES;
            [self goRegisterAction:nil];
        });
        
        return NO;
    }
    
    if ([absoluteString containsString:kWebPageForum]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tabBarController setSelectedIndex:2];
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
        
        return NO;
    }
    
    if ([absoluteString containsString:kInvitationList]) {
        
        if (self.isFromShareList) {
            [self.navigationController popViewControllerAnimated:YES];
            return NO;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([MNDLoginUserModel isUserLogin]) {
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
                MNDInvestListViewController *investListVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDInvestListViewController"];
                investListVC.isFromInvitePage = YES;
                self.isJumpToOtherPage = YES;
                self.isJumpToInvest = YES;
                
                [self.navigationController pushViewController:investListVC animated:YES];
            } else {
                [self goLoginVC];
            }
        });
        return NO;
    }
    
    if ([absoluteString containsString:kQRCodeImage]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *qrCodeUrl = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('oimg').getAttribute('src');"];
            
            NSError *error;
            UIImage *QRImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:qrCodeUrl] options:NSDataReadingMappedAlways error:&error]];
            if (!error) {
                UIImageWriteToSavedPhotosAlbum(QRImage, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
            } else {
                [NetworkProgressHUD showHudMsg:@"图片保存失败"];
            }
        });
        
        return NO;
    }
    return YES;
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [NetworkProgressHUD showHudMsg:@"图片保存失败"];
    } else {
        [NetworkProgressHUD showHudMsg:@"图片保存成功"];
    }
    self.title = _titleStr;
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

- (void)loadEncodeUserCode {
//    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    
    [APIManager sendRequestWithPath:API_ENCODE_USERCODE parameters:[MNDSign signedParamWithDict:@{@"user_code": user.user_code}] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            NSDictionary *dictCookieUId = @{NSHTTPCookieName: @"user_code",
                                            NSHTTPCookieValue: responseModel.data[@"user_code"],
                                            NSHTTPCookieExpires: [NSDate dateWithTimeIntervalSinceNow:60*60*24*365],
                                            NSHTTPCookiePath: @"/",
                                            NSHTTPCookieVersion: @"0",
                                            NSHTTPCookieDomain: @".miniwangdai.com"
                                            };
            NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dictCookieUId];
            
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (NSString *)rsaEncode:(NSString *)rsaStr {
    NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", rsaStr] publicKey:RSA_PUBLIC_KEY];
    NSString *unreserved = @"";
    NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowed addCharactersInString:unreserved];
    
    NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    
    return encodeEncryText;
}

/*! 登录  */
- (void)goLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

/*！ 注册 */
- (IBAction)goRegisterAction:(id)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    MNDRegisterViewController *registerVC = [storyboard instantiateViewControllerWithIdentifier:[MNDRegisterViewController description]];
    [naviVC setViewControllers:@[registerVC] animated:YES];
    registerVC.isNaviRootVC = YES;
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

- (void)socialShareAction {
    
    if (![MNDLoginUserModel isUserLogin]) {
        [self goLoginVC];
        return;
    }
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    [APIManager sendRequestWithPath:API_USER_SHARE parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            NSLog(@"%@", responseModel.data);
            MNDShareModel *shareContent = [MNDShareModel mj_objectWithKeyValues:responseModel.data];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakself shareWithContents:shareContent];
            });
        } else {

            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {

        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)shareWithContents: (MNDShareModel *)content {
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    NSString *encodeUrl = content.share_url;
//    [content.share_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [shareParams SSDKSetupShareParamsByText: content.share_txt
                                     images: content.share_img
                                        url: [NSURL URLWithString:encodeUrl]
                                      title: content.share_title
                                       type: SSDKContentTypeAuto];
    
    [shareParams SSDKSetupWeChatParamsByText: content.share_txt
                                       title: content.share_title
                                         url: [NSURL URLWithString:encodeUrl]
                                  thumbImage: content.share_img
                                       image: content.share_img
                                musicFileURL: nil
                                     extInfo: nil
                                    fileData: nil
                                emoticonData: nil
                                        type: SSDKContentTypeWebPage
                          forPlatformSubType: SSDKPlatformSubTypeWechatSession];

    [shareParams SSDKSetupWeChatParamsByText: content.share_txt
                                       title: content.share_title
                                         url: [NSURL URLWithString:encodeUrl]
                                  thumbImage: content.share_img
                                       image: content.share_img
                                musicFileURL: nil
                                     extInfo: nil
                                    fileData: nil
                                emoticonData: nil
                                        type: SSDKContentTypeWebPage
                          forPlatformSubType: SSDKPlatformSubTypeWechatTimeline];
    
    [shareParams SSDKSetupQQParamsByText: content.share_txt
                                   title: content.share_title
                                     url: [NSURL URLWithString:encodeUrl]
                              thumbImage: content.share_img
                                   image: content.share_img
                                    type: SSDKContentTypeWebPage
                      forPlatformSubType: SSDKPlatformTypeQQ];
    
    //微博分享内容
    [shareParams SSDKSetupSinaWeiboShareParamsByText: content.share_txt
                                               title: content.share_title
                                              images: content.share_img
                                               video: nil
                                                 url: [NSURL URLWithString:encodeUrl]
                                            latitude: 0
                                           longitude: 0
                                            objectID: nil
                                      isShareToStory: NO
                                                type: SSDKContentTypeWebPage];
    
    //使用客户端分享
    [shareParams SSDKEnableUseClientShare];
    
    NSMutableArray *items = [NSMutableArray arrayWithArray:@[@(SSDKPlatformSubTypeWechatSession),
                                                             @(SSDKPlatformSubTypeWechatTimeline),
                                                             @(SSDKPlatformSubTypeQQFriend),
                                                             @(SSDKPlatformTypeSinaWeibo)]];
    
//    __weak typeof(self) weakSelf = self;
    
    //调用分享的方法
    [ShareSDK showShareActionSheet:self.view
                       customItems:items
                       shareParams:shareParams
                sheetConfiguration:nil
                    onStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
        
                        if (platformType == SSDKPlatformTypeSinaWeibo) {
                            if (![WeiboSDK isWeiboAppInstalled]) {
                                NSString  *message = @"您未安装微博客户端, 无法分享";
                                [NetworkProgressHUD showHudMsg:message];
                                return;
                            }
                        }
                        
                        switch (state) {
                            case SSDKResponseStateBegin:
                            {
                                
                                NSLog(@"分享开始");
                            }
                                break;
                            case SSDKResponseStateSuccess:
                            {
                                NSLog(@"分享成功!");
                                [NetworkProgressHUD showHudMsg:@"分享成功"];
                            }
                                
                                break;
                            case SSDKResponseStateFail:
                            {
                                NSLog(@"分享失败%@",error);
                                NSString *errMsg = error.userInfo[@"error_message"];
                                if (!errMsg || [errMsg containsString:@"null"]) {
                                    break;
                                }
                                NSString *message = [NSString stringWithFormat:@"分享失败:%@", error.userInfo[@"error_message"]];
                                [NetworkProgressHUD showHudMsg: message];
                            }
                                break;
                            case SSDKResponseStateCancel:
                            {
                                // [MBProgressHUD showHUDAddedTo:weakSelf.view animated:YES];
                                //MBProgressHUD *HUD = [MBProgressHUD HUDForView:weakSelf.view];
                                // HUD.labelText = @"已取消分享";
                                //HUD.mode = MBProgressHUDModeText;
                                //[HUD hide:YES afterDelay:1.5];
                                NSLog(@"分享已取消");
                            }
                                break;
                            default:
                                break;
                        }
    }];
    //删除和添加平台示例
    //(默认微信，QQ，QQ空间都是直接跳客户端分享，加了这个方法之后，可以跳分享编辑界面分享)
    //        [sheet.directSharePlatforms removeObject:@(SSDKPlatformTypeWechat)];
    //（加了这个方法之后可以不跳分享编辑界面，直接点击分享菜单里的选项，直接分享）
//    [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setCookies {
    if ([MNDLoginUserModel isUserLogin]) {
        //        [self clearWebViewCookies];
        
        MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        
        NSDictionary *dictCookieUId;
        
        dictCookieUId = @{
                          NSHTTPCookieName: @"user_code",
                          NSHTTPCookieValue: user.user_code,
                          NSHTTPCookiePath: @"/",
                          NSHTTPCookieVersion: @"0",
                          NSHTTPCookieDomain: @".miniwangdai.com"
                          };
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dictCookieUId];
        
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
